#include "debug.h"

/**
 * @name USART发送数据
 * @description
 * @function
 * @param {uint8_t} ch 字符
 * @returns {void}
 * @requires [ch]
 */
static void _usart_send(const uint8_t ch) {
    USART_SendData(DEBUG_USART, ch);
    while (USART_GetFlagStatus(DEBUG_USART, USART_FLAG_TXE) != SET) {}
}

/**
 * @name USART接收数据
 * @description
 * @function
 * @returns {uint8_t} 数据
 * @requires []
 */
static uint8_t _usart_recv(void) {
    while (USART_GetFlagStatus(DEBUG_USART, USART_FLAG_RXNE) != SET) {}
    return USART_ReceiveData(DEBUG_USART);
}

/**
 * @name debug初始化
 * @description
 * @function
 * @returns {void}
 * @requires []
 */
void debug_init(void) {
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    USART_InitTypeDef USART_InitStruct = {0};
    // 使能时钟
    DEBUG_RCC_AHBPeriphClockCmd;
    // 配置GPIO
    GPIO_InitStruct.GPIO_Pin = DEBUG_GPIO_Pin;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    // 初始GPIO
    GPIO_Init(DEBUG_GPIO, &GPIO_InitStruct);
    // 配置复用
    GPIO_PinAFConfig(DEBUG_GPIO, DEBUG_USART_RX, DEBUG_GPIO_AF_USART);
    GPIO_PinAFConfig(DEBUG_GPIO, DEBUG_USART_TX, DEBUG_GPIO_AF_USART);
    // 使能时钟
    DEBUG_RCC_APBPeriphClockCmd;
    // 配置USART
    USART_InitStruct.USART_BaudRate = DEBUG_USART_BaudRate;
    USART_InitStruct.USART_WordLength = USART_WordLength_8b;
    USART_InitStruct.USART_StopBits = USART_StopBits_1;
    USART_InitStruct.USART_Parity = USART_Parity_No;
    USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    // 初始USART
    USART_Init(DEBUG_USART, &USART_InitStruct);
    // 使能USART
    USART_Cmd(DEBUG_USART, ENABLE);
}

/**
 * @name debug发送数据
 * @description
 * @function
 * @param {uint8_t} ch 字符
 * @returns {void}
 * @requires [ch]
 */
void debug_send(const uint8_t ch) {
    _usart_send(ch);
}

/**
 * @name debug接收数据
 * @description
 * @function
 * @returns {uint8_t} 数据
 * @requires []
 */
uint8_t debug_recv(void) {
    return _usart_recv();
}